package com.jasperframework.boot.file.service;

import com.jasperframework.boot.file.PathGen;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

@Service
@Slf4j
public class FmsService {

    /**
     * 根路径
     */
    @Value("${fms.baseDir}")
    private String baseDir;

    /**
     *
     * @param originName 	 上传文件
     * @param folder        文件夹分类名称（例如：默认分类为根文件夹：''，头像分类：systemAvatar#1级子文件夹#2级子文件夹#...）
     * @param content	    文件字节数组
     * @return
     */
    public String saveFile(String originName, String folder, boolean useOriginNameAsPrefix, byte[] content) {
        String path = StringUtils.isNotBlank(folder)
                ? PathGen.getPath(originName, folder, useOriginNameAsPrefix)
                : PathGen.getPath(originName);
        File f = new File(baseDir + path);
        if (!f.exists()) {
            try {
                File fileParent = f.getParentFile();
                if (!fileParent.exists()) {
                    fileParent.mkdirs();
                }
                f.createNewFile();
            } catch (IOException e1) {
                log.error("saveFile exception=【{}】", e1.getMessage());
            }
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(f);
            StreamUtils.copy(content, out);
        } catch (Exception e) {
            log.error("StreamUtils.copy exception=【{}】", e.getMessage());
        }finally {
            if(out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    log.error("StreamUtils.copy exception=【{}】", e.getMessage());
                }
            }
        }
        return path;
    }

    public byte[] getFile(String path) {
        File f = new File(baseDir + path);
        byte[] content = null;
        try {
            content = StreamUtils.copyToByteArray(new FileInputStream(f));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("StreamUtils.copyToByteArray exception=【{}】", e.getMessage());
        }
        return content;
    }

    public String getUrl(String path) {
        return path;
    }
}
